<?php
require(dirname(__FILE__) . '/includes/init.php');
if($_REQUEST['act'] == 'send'){
	$user_list = $db->getAll("select s.*,a.active_name from ".$ecs->table('send_user')."as s left join ".$ecs->table('active_type')." as a on s.active_id=a.active_id where a.active_id='".$_REQUEST['active_id']."'");
	if(count($user_list)>0){
		foreach($user_list as $user){
			if($user['buy_num']<=1 and $user['send_num']>=$_REQUEST['send_sel']){
				//do nothing
			}else{
				//发送数据
				require_once('includes/cls_sms.php');
				$sms = new sms();
				$msg = '尊敬的'.$user['user_name'].','.$_POST['msg'].'【悦国红酒】';
				$ok = $sms->send($user['mobile'],$msg); 
				if($ok){
					//插入数据库
					$money = $db->getOne("select money from ".$ecs->table('search_order')." where order_id='".$user['order_id']."'");
    				$db->query("insert into ".$ecs->table('send_detail')." (active_name,active_id,msg,profit,money,send_time) values('".$user['active_name']."','".$user['active_id']."','".$msg."','".$_POST['profit']."','".$money."','".time()."')");
					$db->query("update ".$ecs->table('send_user')." set send_num=send_num+1 where active_id='".$user['user_id']."'");
					sleep($_POST['frequency']);
				}
			}
		}
	}
}else if($_REQUEST['act'] == 'read'){
	if(trim($_POST['parent_active_name'])!=''){
		$active_id = $db->getOne("select active_id from ".$ecs->table('active_type')." where active_name='".$_POST['parent_active_name']."'");
		if(empty($active_id)){
			$db->query("insert into ".$ecs->table('active_type')." (active_name,parent) values ('".$_POST['parent_active_name']."',0)");
			$new_id = $db->insert_id();
			$db->query("insert into ".$ecs->table('active_type')." (active_name,parent) values ('".$_POST['parent_active_name'].'--1'."','".$new_id."')");
			$child_id = $db->insert_id();
		}else{
			$num = $db->getOne("select count(active_id) as num from ".$ecs->table('active_type')." where parent='".$active_id."'");
			$db->query("insert into ".$ecs->table('active_type')." (active_name,parent) values ('".$_POST['parent_active_name'].'--'.($num+1)."','".$active_id."')");
			$child_id = $db->insert_id();
		}
		//导入数据
		require_once('includes/cls_readexcel.php'); 
		$data= new Spreadsheet_Excel_Reader(); 
		$data->setOutputEncoding('utf-8'); 
		if ($_FILES["file"]["error"] > 0){
			$error = urlencode('文件出错了，错误码：'.$_FILES["file"]["error"]);
			header("Location: active_send.php?error=$error\n");exit;
		}else if(end(explode(".",strtolower($_FILES["file"]['name'])))!='xls'){
			$error = urlencode('请选择excel文件');
			header("Location: active_send.php?error=$error\n");exit;
		}else{
			$datapath = $_FILES["file"]["tmp_name"];
		}
		$data->read($datapath);
		$count = 1;
		$ok = false;
		for($i= 2; $i<= $data->sheets[0]['numRows']; $i++){
			//查询手机号对应的购买次数的最大值
			$max_buy_num = $db->getOne("select buy_num from ".$ecs->table('send_user')." where mobile='".$data->sheets[0]['cells'][$i][3]."' order by buy_num desc limit 1");
			if(!$max_buy_num){
				$max_buy_num = 0;
			}
			$sql = "INSERT INTO " .$ecs->table('send_user')." (active_id,order_id,user_name,mobile,buy_num) values('".$child_id."','".$data->sheets[0]['cells'][$i][1]."','".$data->sheets[0]['cells'][$i][2]."','".$data->sheets[0]['cells'][$i][3]."','".($max_buy_num+1)."')";
			$ok = $db->query($sql);
			if($ok){
				$count++;
			}
		}
		$dao_str = '已成功导入'.$count.'条';
	}
}

$parent_active_list = $db->getAll("select active_name from ".$ecs->table('active_type')."where parent=0 order by active_id desc");
$active_list = $db->getAll("select active_name from ".$ecs->table('active_type')."where parent<>0 order by active_id desc");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>管理中心 - 短信群发 </title>
<meta name="robots" content="noindex, nofollow">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="styles/general.css" rel="stylesheet" type="text/css" />
<link href="styles/main.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/common.js"></script>
</head>
<body>
<h1>
<span class="action-span1"><a href="index.php?act=main">管理中心</a> </span><span id="search_id" class="action-span1"> - 短信群发 </span>
<div style="clear:both"></div>
</h1>
<?php if(!empty($_GET['error'])){?>
<div class="form-div" id="error">
  <span><a href="#" onclick="javascript:err_hide()" title="关闭"><img src="images/no.gif" border="0" alt="关闭"></a><?php echo urldecode($_GET['error']); ?></span>
</div>
<?php }?>
<div class="tab-div">
	<div id="tabbody-div">
  <form method="post" action="active_send.php?act=read" enctype="multipart/form-data" onsubmit="return check_title_form()">
  <table width="100%" align="center">
  <tr>
  <td>活动父标题：</td>
  <td><div id="change"><select name="parent_active_name" id="selecter">
					<option value="">请选择...</option>
					<?php
					if(count($parent_active_list)>0){
						foreach($parent_active_list as $active){
					?> 
							<option value="<?php echo $active['active_name'];?>"><?php echo $active['active_name'];?></option>
					<?php
						}
					}
					?>		
				</select>
				<input type="button" value="添加标题" class="button" id="changeItem" onclick="type_change()" />
				</div>
	</td>
	</tr>
	<tr>			
   <td>Excel：</td>
   <td><input type="file" name="file" size="50" id="excel_file" />(导入数据请到客户跟踪-订单列表下载)</td>
   </tr>
   </table>
   <div class="button-div">
   <input type="submit" name="readexcel" value="导入" class="button"/>
   <?php if($dao_str){?><span style="color:red;"><?php echo $dao_str;?></span><?php }?>
   </div>
  </form>
  </div>
</div>
 
<div class="tab-div">
	<div id="tabbody-div">
		 <form action="active_send.php?act=send" method="post" onsubmit="return check_send_form()">
		 <table width="100%" id="general-table" align="center">
			<tr>
				<td class="label">活动标题:</td>
				<td>
				<select name="active_id" id="active_id">
					<?php
					if(count($active_list)>0){
						foreach($active_list as $active1){
					?> 
						<option value="<?php echo $active1['active_name'];?>"><?php echo $active1['active_name'];?></option>
					<?php 
						}
					}
					?>
				</select>	
				</td>
			</tr>
			<tr>
				<td class="label">短信内容:</td>
				<td><textarea name="msg" id="msg"></textarea></td>
			</tr>
			<tr>
				<td class="label">发送选项:</td>
				<td>
				<select name="send_sel" id="send_sel">
				<option value="">请选择...</option>
				<option value="0">0</option>
				<option value="1">1</option>
				<option value="2">2</option>
				<option value="3">3</option>
				<option value="4">4</option>
				<option value="5">5</option>
				<option value="6">6</option>
				<option value="7">7</option>
				<option value="8">8</option>
				<option value="9">9</option>
				</select>(大于n次没购买的不发送)
				</td>
			</tr>
			<tr>
				<td class="label">平均净利:</td>
				<td><input type="text" name="profit" id="profit" />(格式：小于1的小数，eg:0.8)</td>
			</tr>
			<tr>
				<td class="label">发送频率:</td>
				<td><input type="text" name="frequency" size="4"/>秒</td>
			</tr>
	  	</table>
		<div class="button-div">
          <input type="submit" value=" 确定 " class="button" />
          <input type="reset" value=" 重置 " class="button" />
        </div>
		</form>
	</div>
</div>

<script type="text/javascript">  
	function type_change(){
	    $("#selecter").remove();
		$("#changeItem").remove();
		$("#change").append("<input type='text' name='parent_active_name' size='40' id='inputer' />");
		if($("#changeItem").attr("value") == "添加标题"){  
            $("#changeItem").val("选择标题") ;  
        }  
        else{  
            $("#changeItem").val("添加标题") ;  
        }  
	}
	function err_hide(){
	 $("#error").css("display","none"); 
	}
	function check_title_form(){
		var selecter_val= $("#selecter").val();
		var inputer_val = $("#inputer").val();
		var excel_file = $("#excel_file").val();
		var msg = '';
		if((inputer_val==undefined&&selecter_val==0)||(inputer_val.length==0&&selecter_val==undefined)){
			msg += '请输入或者选择活动父标题\n'; 	
		}
		if(excel_file.length<=0){
			msg += '请选择excel文件\n'; 
		}
		if(msg.length>0){
			alert(msg);
			return false;
		}else{
			return true;
		}
	}
	
	function check_send_form(){
		var msg = $("#msg").val();
		var send_sel = $("#send_sel").val();
		var profit = $("#profit").val();
		var frequency = $("#frequency").val();
		var error = '';
		if(msg.length<=0){
			error += '请输入短信内容\n';
		}
		if(send_sel==''){
			error += '请选择发送选项\n';
		}
		if(profit.length<=0|(profit<=0|profit>=1)){
			error += '平均净利输入值有误，值要0<n<1\n';
		}
		var re = /^\+?[1-9][0-9]*$/;
		if(!re.test(frequency)){
			error += '发送频率请输入整数';
		}
		if (error.length > 0)
		{
			alert(error);
			return false;
		}
		else
		{
			return true;
		}
	}
	
</script>  

</body>
</html>